package com.mi.global.shop.common.utils;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.v7.app.NotificationCompat;
import android.text.TextUtils;
import android.widget.RemoteViews;


import com.google.gson.Gson;
import com.mi.global.shop.MainActivity;
import com.mi.global.shop.R;
import com.mi.global.shop.common.bean.Constants;
import com.mi.global.shop.common.bean.CustomNotificationContent;


import java.util.List;


/**
 * Created by suzeyao on 6/1/17.
 */

public class CustomNotificationUtil {
    private static int notificationID = 1;
    private static final float ASPECT_RATIO = 3.84f;
    private static int imageWidth = 0;
    private static int imageHeight = 0;

    public static void handleCustomNotificationContent(Context context, String content) {
        final CustomNotificationContent notificationContent = parseNotificationContent(content);
        if (null == notificationContent)
            return;
//        LogUtil.d(notificationContent.toString());

        final Context appContext = context.getApplicationContext();
        // load icon
        String iconUrl = notificationContent.getIconUrl();
        FrescoUtils.getBitmap(iconUrl, appContext, new FrescoUtils.BitmapListener() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                onLoadIconSuccess(appContext, bitmap, notificationContent);
            }

            @Override
            public void onFail() {
            }
        });
    }

    private static void onLoadIconSuccess(final Context appContext, final Bitmap icon, final CustomNotificationContent notificationContent) {
        final List<CustomNotificationContent.Data> data = notificationContent.getData();
        if (null == data || data.size() == 0)
            return;

        for (int i = 0; i < data.size(); i++) {
            final CustomNotificationContent.Data item = data.get(i);
            switch (item.getType()) {
                case CustomNotificationContent.Data.TEXT: {
                    item.setCompleted(true);
                    if (checkComplete(data)) {
                        sendCustomNotification(appContext, icon, notificationContent);
                    }
                    break;
                }
                case CustomNotificationContent.Data.IMAGE: {
                    // load image
                    String url = item.getContent();
                    FrescoUtils.getBitmap(url, appContext, getImageViewWidth(), getImageViewHeight(), new FrescoUtils.BitmapListener() {
                        @Override
                        public void onSuccess(Bitmap bitmap) {
                            item.setBitmap(bitmap);
                            item.setCompleted(true);
                            if (checkComplete(data)) {
                                sendCustomNotification(appContext, icon, notificationContent);
                            }
                        }

                        @Override
                        public void onFail() {
                        }
                    });
                    break;
                }
            }
        }
    }

    private static boolean checkComplete(List<CustomNotificationContent.Data> data) {
        for (CustomNotificationContent.Data item : data) {
            if (!item.isCompleted())
                return false;
        }
        return true;
    }

    private static void sendCustomNotification(Context context, Bitmap icon, CustomNotificationContent notificationContent) {
        //SDK 16以后才支持
        if (Build.VERSION.SDK_INT < 15)
            return;

        //1.设置点击触发的 intent
        PendingIntent pIntent = createPendingIntent(context, notificationContent.getUrl());

        String title = notificationContent.getTitle();
        String content = null;
        // 2 设置自定义 view
        RemoteViews rv = new RemoteViews(context.getPackageName(), getCustomNotificationLayout());
        rv.setImageViewBitmap(R.id.iv_icon, icon);
        rv.setTextViewText(R.id.tv_title, title);
        rv.setTextViewText(R.id.tv_time, TimeFormaterUtil.formatNotificationTime(System.currentTimeMillis()));
        // 设置颜色
        int[] textColors = NotificationTextColorUtils.getNotificationTextColor(context);
        rv.setTextColor(R.id.tv_title, textColors[0]);
        rv.setTextColor(R.id.tv_time, textColors[1]);
        // data
        for (CustomNotificationContent.Data item : notificationContent.getData()) {
            switch (item.getType()) {
                case CustomNotificationContent.Data.TEXT: {
                    if (null == content) {
                        content = item.getContent();
                    }
                    // create tv
                    RemoteViews tv = new RemoteViews(context.getPackageName(), R.layout.push_notification_text);
                    tv.setTextViewText(R.id.tv_content, item.getContent());
                    tv.setTextColor(R.id.tv_content, textColors[1]);
                    rv.addView(R.id.v_container, tv);
                    break;
                }
                case CustomNotificationContent.Data.IMAGE: {
                    // create iv
                    RemoteViews iv = new RemoteViews(context.getPackageName(), R.layout.push_notification_image);
                    iv.setImageViewBitmap(R.id.iv_content, item.getBitmap());
                    iv.setInt(R.id.iv_content, "setMaxHeight", getImageViewHeight());
                    rv.addView(R.id.v_container, iv);
                    break;
                }
            }
        }

        // 3. 发送通知
        sendNotificationWithRemoteView(context, icon, title, content, pIntent, rv);
    }

    private static int getImageViewWidth() {
        if (imageWidth == 0) {
            imageWidth = ScreenInfo.getInstance().getScreenWidth() - PtrLocalDisplay.dp2px(100);
        }
        return imageWidth;
    }

    private static int getImageViewHeight() {
        if (imageHeight == 0) {
            imageHeight = (int) (getImageViewWidth() / ASPECT_RATIO);
        }
        return imageHeight;
    }


    public static CustomNotificationContent parseNotificationContent(String content) {
        try {
            return new Gson().fromJson(content, CustomNotificationContent.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static int getCustomNotificationLayout() {
        int layout = 0;
        if (Device.IS_MIUI) {
            layout = R.layout.push_notification_layout_style_miui;
        } else {
            layout = R.layout.push_notification_layout_style_other;
        }
        return layout;
    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private static void sendNotificationWithRemoteView(Context context, Bitmap icon, CharSequence title, CharSequence content,
                                                       PendingIntent pIntent, RemoteViews rv) {
        // 创建 Notification
        NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.icon_logo)// status bar icon
                .setLargeIcon(icon)
                .setContentTitle(title)
                .setContentText(content)
                .setContentIntent(pIntent)
                .setFullScreenIntent(null, false)// 浮动通知
//                .setVisibility(Notification.VISIBILITY_PUBLIC)// 锁屏通知
                .setAutoCancel(true)
//                .setCustomContentView(rv)
//                .setCustomBigContentView(rv)
                .setWhen(System.currentTimeMillis())
                .build();

        notification.bigContentView = rv;

        // 将Notification发给Manager
        nManager.notify(notificationID++, notification);
    }

    private static PendingIntent createPendingIntent(Context context, String url) {
        if (TextUtils.isEmpty(url))
            return null;
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Constants.Intent.ACTION_SHOW_M_SITE);
        intent.putExtra("url", url);
        return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
}
